"use client";

import LoadingPage from "@/components/loadingpage";
import { FastResponse } from "@/components/models/dataprops";
import { ServerErrorPanel } from "@/components/ServerError";
import { useSidebarStore } from "@/components/state/sidebar_state";
import {
  Table,
  TableBody,
  TableCaption,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { getData } from "@/components/utils/api";
import { useEffect, useState } from "react";

// 根据版本号获得所有的结果

function ResultPage() {
  const updateSelected = useSidebarStore((state) => state.updateSelected);
  const [requestError, setRequestError] = useState(false);
  const [resultDict, setResultDict] = useState("");

  useEffect(() => {
    updateSelected("调优结果", "大模型调度");

    // 获取所有结果
    const queryResults = async () => {
      try {
        const results = await getData<FastResponse<string>>(
          "/model/result/all"
        ); // 泛型定义请求和响应类型
        if (results.code == 200) {
          console.log(results.data);
          setResultDict(results.data);
        }
        setRequestError(false);
      } catch (error) {
        console.log("Error submitting data:", error);
        setRequestError(true);
      }
    };

    queryResults();
  }, [updateSelected]);

  return (
    <div className="flex flex-flow items-center justify-center gap-2">
      {resultDict != "" ? (
        <>
          {Object.entries(resultDict).map(([key, value]) => {
            return (
              <div
                key={key}
                className="flex flex-col items-center justify-center"
              >
                <div className="text-lg">{key}</div>
                <div className="text-lg">
                  <Table>
                    <TableCaption>
                      result on task -{" "}
                      <span className="text-black text-bold text-lg">
                        {key}.
                      </span>
                    </TableCaption>
                    <TableHeader>
                      <TableRow>
                        <TableHead className="w-[100px]">version</TableHead>
                        <TableHead className="w-[400px]">result</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {Object.entries(value).map(([v, r]) => (
                        <TableRow key={v}>
                          <TableCell className="font-medium">{v}</TableCell>
                          <TableCell>{JSON.stringify(r)}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </div>
            );
          })}
        </>
      ) : requestError ? (
        <ServerErrorPanel />
      ) : (
        <LoadingPage />
      )}
    </div>
  );
}

export default ResultPage;
